package org.softmed.rest.server.xstream;

import java.util.HashMap;
import java.util.Map;
import org.softmed.persistence.PersistenceManager;
import org.softmed.rest.config.Application;
import org.softmed.rest.generation.xml.XMLMarshaller;

public class ListItemToXML implements XMLMarshaller {

	static Map<Class, XMLMarshaller> converters = new HashMap<Class, XMLMarshaller>();
	Map<Class, XMLMarshaller> myConverters = new HashMap<Class, XMLMarshaller>();
	XMLMarshaller converter;

	Class current = null;
	Class previous = null;

	public ListItemToXML() {
		myConverters.putAll(converters);
	}

	public String toXML(Object obj, PersistenceManager odbUtil,
			Application app, Object... options) throws Throwable {

		chooseConverter(obj.getClass(), odbUtil, app, options);

		return converter.toXML(obj, odbUtil, app);
	}

	private void chooseConverter(Class type, PersistenceManager odbUtil,
			Application app, Object... options) throws Throwable {
		current = type;
		if (converter != null) {
			if (current == previous)
				return;
			previous = current;
		}

		converter = converters.get(current);

		if (converter == null) {
			converter = // new DefaultToXMLListItemConverter();
			XMLCache.getListConverter(type, odbUtil, app, options);
		}
		// else
		// converter = converter.clone();

	}

	public static Map<Class, XMLMarshaller> getConverters() {
		return converters;
	}

	public ListItemToXML clone() {
		return new ListItemToXML();

	}

}
